package net.htjs.juc.chapter04;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class DemoSynchronizedMethod {


    /**
     * 线程1运行完,线程2再运行，Synchronized包裹的代码具有原子性，不可分割
     * @param args
     */
    public static void main(String[] args) {
        Room room = new Room();
        try {
            Thread t1 = new Thread(() -> {
                for(int i = 0; i < 10000; i++){
                    room.increment();
                }
            }, "t1");
            Thread t2 = new Thread(() -> {
                for(int i = 0; i < 10000; i++){
                    room.decrement();
                }
            }, "t2");
            t1.start();
            t2.start();
            t1.join();
            t2.join();
            log.info("counter:{}", room.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    static class Room {
        private int counter = 0;

        /**
         * synchronized加在成员方法上相当于加到了当前对象this身上
         * synchronized加在静态方法上，锁住的是当前类对象
         */
        public synchronized void increment() {
            counter++;
            log.info("counter:{}", counter);
        }

        public synchronized void decrement() {
            counter--;
            log.info("counter:{}", counter);
        }

        public synchronized int get() {
            return counter;
        }
    }
}
